package yannan.voiplock4ble;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.sharesdk.framework.ShareSDK;
import io.github.yavski.fabspeeddial.FabSpeedDial;
import io.github.yavski.fabspeeddial.SimpleMenuListenerAdapter;
import yannan.voiplock4ble.base.BaseFragment;
import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.LoggedBaseActivity;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.base.MyEnum;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.bean.ble.ConnectLock;
import yannan.voiplock4ble.db.MyDBHelper;
import yannan.voiplock4ble.eventbus.BaseEventMsg;
import yannan.voiplock4ble.eventbus.MainMsg;
import yannan.voiplock4ble.eventbus.OperAdminMsg;
import yannan.voiplock4ble.eventbus.SearchLockBleMsg;
import yannan.voiplock4ble.fragment.AboutUsFragment;
import yannan.voiplock4ble.fragment.LeftMenuFragment;
import yannan.voiplock4ble.fragment.LockKeyPwdFragment;
import yannan.voiplock4ble.fragment.LockKeyVeinFragment;
import yannan.voiplock4ble.fragment.LockListFragment;
import yannan.voiplock4ble.fragment.LockRecordFragment;
import yannan.voiplock4ble.service.ble.BleOperUtils;
import yannan.voiplock4ble.service.ble.BleService;
import yannan.voiplock4ble.service.ble.BleUtils;
import yannan.voiplock4ble.utils.DeviceUtils;
import yannan.voiplock4ble.utils.LogUtils;
import yannan.voiplock4ble.utils.PopShowUtils;
import yannan.voiplock4ble.utils.ToastUtils;
import yannan.voiplock4ble.view.ScrollAwareFABBehaviorDefault;

@Content(R.layout.activity_main)
public class MainActivity extends LoggedBaseActivity implements View.OnClickListener, LeftMenuFragment.onLeftMenuChecked {

    @Bind(R.id.tv_title_name)
    TextView tv_title_name;
    @Bind(R.id.tv_lock_name)
    TextView tv_lock_name;
    @Bind(R.id.img_lock_name)
    ImageView img_lock_name;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawer;
    @Bind(R.id.fab_add)
    public FabSpeedDial fab_add;
    @Bind(R.id.title_left)
    LinearLayout title_left;
    @Bind(R.id.title_right)
    LinearLayout title_right;
    @Bind(R.id.iv_left)
    ImageView iv_left;
    @Bind(R.id.fl_conant_bg)
    FrameLayout fl_conant_bg;
    @Bind(R.id.lv_lock_list)
    ListView lv_lock_list;

    public BleService mBleService;
    public List<LockBean> lockBeanList;
    public LockBean lockBeanNow;
    public boolean isHaveLock;
    private LeftMenuFragment leftMenuFragment;
    BaseFragment lastShowFragment;
    LockKeyVeinFragment lockVeinKeyFragment;
    LockKeyPwdFragment lockPwdKeyFragment;
    AboutUsFragment aboutUsFragment;
    LockListFragment lockListFragment;
    LockRecordFragment lockRecordFragment;
    long clickTime;
    MyReceive mMyReceive = new MyReceive();
    boolean isActive = true;

    static MainActivity mainActivity;

    public static MainActivity getMainActivity() {
        return mainActivity;
    }

    @Override
    public void initData() {
        setTitleTheme(TitleTheme.TOOLBAR_THEME_HOME, "");
        iv_left.setBackgroundResource(R.drawable.ic_menu_white_24dp);
        FrameLayout rl_title_root = (FrameLayout) findViewById(R.id.fl_conant);
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) rl_title_root.getLayoutParams();
        lp.setMargins(0, DeviceUtils.getTopBarHeight(this), 0, 0);
        rl_title_root.setLayoutParams(lp);
        fl_conant_bg.setClickable(false);
        if (this.mBleService == null)
            bindService(new Intent(this, BleService.class), this.mConn, Context.BIND_AUTO_CREATE);
        lockBeanList = new ArrayList<>();
        lockBeanList = (List<LockBean>) getIntent().getSerializableExtra(MyEnum.MainEnum.lockBeanList.toString());
        ShareSDK.initSDK(mContext, "19ee0797661fe");
        MobclickAgent.onProfileSignIn(MyApplication.getInterface().userBean.getUserId());
        initView();
        initLeftNav();
        mainActivity = this;
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkBluetooth();
        MobclickAgent.onResume(this);
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mMyReceive, mIntentFilter);
        isActive = true;
        lv_lock_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!lockBeanList.get(position).equals(lockBeanNow)) {
                    changeLock(position);
                } else {
                    ToastUtils.showToast(mContext, "不用切换锁");
                    closeTitleList();
                }
            }
        });
        fadClick();
        clickTime = System.currentTimeMillis();
    }

    /**
     * 切换锁
     * 标题修改
     * 蓝牙指示状态改变
     * 三个页面内容清空
     * 自动开始链接
     *
     * @param position
     */
    private void changeLock(int position) {
        ToastUtils.showToast(MainActivity.this, "切换锁位置" + lockBeanList.get(position).getMac());
        closeTitleList();
        lockBeanNow = lockBeanList.get(position);
        tv_lock_name.setText(lockBeanList.get(position).getLockName());
        //断开链接，会自动修改蓝牙指示状态
        mBleService.disConnect();
        i = 0;
        isAutoConnect = false;
        handler.sendEmptyMessageDelayed(RE_CONNECT_LOCK, 10000);
        EventBus.getDefault().post("changeLockMsg");
    }

    private void closeTitleList() {
        fl_conant_bg.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        fl_conant_bg.setClickable(false);
        titleView.closeList();
    }

    /**
     * 检查蓝牙权限 适配6.0
     */
    private void checkBluetooth() {
        if (!DeviceUtils.checkPermission(this)) {
            DeviceUtils.requestPermission(this);
        }
    }

    /**
     * FAD按钮点击事件
     */
    private void fadClick() {
        fab_add.setMenuListener(new SimpleMenuListenerAdapter() {
            @Override
            public boolean onMenuItemSelected(MenuItem menuItem) {
                if (BleOperUtils.checkBleConnect(lockBeanNow)) {
                    Intent intent = new Intent();
                    intent.setClass(mContext, AddPwdOrVeinActivity.class);
                    switch (menuItem.getItemId()) {
                        case R.id.fab_add_pwd:
                            intent.putExtra("type", "pwd");
                            break;
                        case R.id.fab_add_vein:
                            intent.putExtra("type", "vein");
                            break;
                    }
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, "门锁未连接");
                }
                return false;
            }
        });
    }

    /**
     * 初始化左边菜单栏
     */
    private void initLeftNav() {
        isHaveLock = true;
        leftMenuFragment = new LeftMenuFragment();
        if (null == lockBeanList || lockBeanList.size() == 0) {
            leftMenuFragment.id = R.id.tv_lock_list;
        } else {
            refreshLockList();
            leftMenuFragment.id = R.id.tv_lock_record;
            lockBeanNow = lockBeanList.get(0);
            isHaveLock = true;
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.nav_content, leftMenuFragment).commit();
    }

    private void refreshLockList() {
        List<String> itemList = new ArrayList<>();
        for (LockBean item :
                lockBeanList) {
            itemList.add(item.lockName);
        }
        ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
                R.layout.item_title, R.id.text, itemList);//适配器
        lv_lock_list.setAdapter(myAdapter);
    }

    /**
     * 初始化布局
     */
    private void initView() {
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 设置标题
     *
     * @param titleName
     */
    private void changeTitle(String titleName) {
        if (titleName.equals("")) {
            title_right.setVisibility(View.VISIBLE);
            tv_lock_name.setVisibility(View.VISIBLE);
            img_lock_name.setVisibility(View.VISIBLE);
            tv_lock_name.setText(lockBeanNow.lockName);
            tv_title_name.setVisibility(View.GONE);
        } else {
            title_right.setVisibility(View.GONE);
            tv_lock_name.setVisibility(View.GONE);
            img_lock_name.setVisibility(View.GONE);
            tv_title_name.setText(titleName);
            tv_title_name.setVisibility(View.VISIBLE);
        }
    }

    public void closeDrawer() {
        drawer.closeDrawer(GravityCompat.START);
    }

    @OnClick({R.id.tv_lock_name, R.id.title_left, R.id.title_right, R.id.fl_conant_bg})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_lock_name:
                if (titleView.isOpen) {
                    closeTitleList();

                } else {
                    titleView.openList();
                    fl_conant_bg.setClickable(true);
                    fl_conant_bg.setBackgroundColor(getResources().getColor(R.color.color_transparent_gray));
                }
                break;
            case R.id.title_right:
                // TODO: 2017/2/20 弹出pop
                PopShowUtils.showPopuWindow(R.layout.popu_main_setting, this, findViewById(R.id.title_right),
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                switch (v.getId()) {
                                    case R.id.popu_main_setting:
                                        startActivity(new Intent(MainActivity.this, LockSettingActivity.class).putExtra("lockBean", lockBeanNow));
                                        break;
                                    case R.id.popu_main_pwd:
                                        if (BleOperUtils.checkBleConnect(lockBeanNow)) {
                                            mBleService.sendOrder(BleUtils.changeAdminPwd(MyApplication.getInterface().mConnectLock.contentToken));
                                        }
                                        break;
                                    case R.id.popu_main_connect:
                                        if (lockBeanNow != null && lockBeanNow.getMac() != null) {
                                            mBleService.connectLock(lockBeanNow.getMac());
                                            MyApplication.getInterface().mConnectLock = new ConnectLock(new byte[0], lockBeanNow.getLockserialId());
                                        }
                                        break;
                                    case R.id.popu_main_disconnect:
                                        ToastUtils.showToast(mContext, "断开连接");
                                        mBleService.disConnect();
                                        break;
                                }
                            }
                        }, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,
                        R.id.popu_main_pwd,
                        R.id.popu_main_setting,
                        R.id.popu_main_connect,
                        R.id.popu_main_disconnect);
                break;
            case R.id.title_left:
                drawer.openDrawer(GravityCompat.START);
                break;
            case R.id.fl_conant_bg:
                if (titleView.isOpen) {
                }
                closeTitleList();
                break;
        }
    }

    private ServiceConnection mConn = new ServiceConnection() {
        public void onServiceConnected(ComponentName paramComponentName, IBinder paramIBinder) {
            MainActivity.this.mBleService = ((BleService.BleBinder) paramIBinder).getService();
            if (lockBeanNow != null && lockBeanNow.getMac() != null) {
                //自动连接
                mBleService.connectLock(lockBeanNow.getMac());
                MyApplication.getInterface().mConnectLock = new ConnectLock(new byte[0], lockBeanNow.getLockserialId());
                handler.sendEmptyMessageDelayed(RE_CONNECT_LOCK, 10000);
                isAutoConnect = false;
            }
        }

        public void onServiceDisconnected(ComponentName paramComponentName) {
            mBleService = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mMyReceive);
        if (mBleService != null) {
            unbindService(mConn);
            mBleService.stopSelf();
        }
        MyApplication.getInterface().mConnectLock = null;
    }

    final int RE_CONNECT_LOCK = 1101;
    public boolean isAutoConnect = false;  //是否自动连接成功，
    int i = 0;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RE_CONNECT_LOCK:
                    if (!isAutoConnect && lockBeanNow != null && i < 5) {
                        i++;
                        if (BuildConfig.DEBUG)
                            Log.e("MainActivity", "RE_CONNECT_LOCK" + lockBeanNow.getMac());
                        MyApplication.getInterface().mConnectLock = new ConnectLock(new byte[0], lockBeanNow.getLockserialId());
                        mBleService.connectLock(lockBeanNow.getMac());
                        handler.sendEmptyMessageDelayed(RE_CONNECT_LOCK, 10000);
                        isAutoConnect = false;
                    }
                    break;
            }
        }
    };

    @Override
    public void lockRecord() {
//        ScrollAwareFABBehaviorDefault.isNeedVisible = false;
        if (iOnMenuChangeLisenter != null) {
            iOnMenuChangeLisenter.ChangeMenu(false);
        }

        //修改滑动列表时候，标题的效果
        changeTitle("");
        fab_add.hide();
        if (null == lockRecordFragment) {
            lockRecordFragment = new LockRecordFragment();
            showHideFragment(lockRecordFragment, true);
        } else {
            showHideFragment(lockRecordFragment, false);
        }
    }

    @Override
    public void veinKey() {
//        ScrollAwareFABBehaviorDefault.isNeedVisible = true;
        if (iOnMenuChangeLisenter != null) {

            iOnMenuChangeLisenter.ChangeMenu(true);
        }
        //指静脉钥匙
        changeTitle("");
        fab_add.show();
        if (null == lockVeinKeyFragment) {
            lockVeinKeyFragment = new LockKeyVeinFragment();
            showHideFragment(lockVeinKeyFragment, true);
        } else {
            showHideFragment(lockVeinKeyFragment, false);
        }
    }

    @Override
    public void pwdKey() {
//        ScrollAwareFABBehaviorDefault.isNeedVisible = true;
        if (iOnMenuChangeLisenter != null) {

            iOnMenuChangeLisenter.ChangeMenu(true);
        }
        //密码钥匙
        changeTitle("");
        fab_add.show();
        if (null == lockPwdKeyFragment) {
            lockPwdKeyFragment = new LockKeyPwdFragment();
            showHideFragment(lockPwdKeyFragment, true);
        } else {
            showHideFragment(lockPwdKeyFragment, false);
        }
    }

    @Override
    public void lockList() {
//        ScrollAwareFABBehaviorDefault.isNeedVisible = true;
        if (iOnMenuChangeLisenter != null) {

            iOnMenuChangeLisenter.ChangeMenu(false);
        }
        changeTitle("门锁列表");
        fab_add.hide();
        if (null == lockListFragment) {
            lockListFragment = new LockListFragment();
            showHideFragment(lockListFragment, true);
        } else {
            showHideFragment(lockListFragment, false);
        }
    }

//    @Override
//    public void aboutUs() {
//        //关于我们
//        changeTitle("关于我们");
//        if (null == aboutUsFragment) {
//            aboutUsFragment = new AboutUsFragment();
//            showHideFragment(aboutUsFragment, true);
//        } else {
//            showHideFragment(aboutUsFragment, false);
//        }
//    }

    /**
     * 切换Fragment
     *
     * @param show
     * @param isFirst
     */
    private void showHideFragment(BaseFragment show, boolean isFirst) {
        if (titleView.isOpen) {
            closeTitleList();
        }
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (isFirst) {
            ft.add(R.id.fl_conant, show);
        } else {
            ft.show(show);
        }
        if (lastShowFragment != null) {
            ft.hide(lastShowFragment);
        }
        lastShowFragment = show;
//        ft.commit();
        ft.commitAllowingStateLoss();
        invalidateOptionsMenu();
        drawer.closeDrawer(GravityCompat.START);
    }

    public static interface OnActivityResultFrag {
        void onActivityResultFrag(int requestCode, int resultCode, Intent data);
    }

    OnActivityResultFrag onFragmentResult;

    public void setOnActivityResultFrag(OnActivityResultFrag onFragmentResult) {
        this.onFragmentResult = onFragmentResult;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (onFragmentResult != null && data != null)
            onFragmentResult.onActivityResultFrag(requestCode, resultCode, data);
    }

    /**
     * 切換門鎖
     *
     * @param id
     */
    public void changeMenu(int id) {
        if (leftMenuFragment != null) {
            leftMenuFragment.setCheck(id);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
            return false;
        } else if (titleView.isOpen) {
            closeTitleList();
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            long time = System.currentTimeMillis();
            if (time - clickTime > 2000) {
                ToastUtils.showToast(mContext, "再次点击退出");
                clickTime = time;
                return false;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEventMsg baseMsg) {
        if (baseMsg instanceof MainMsg) {
            MainMsg msg = (MainMsg) baseMsg;
            if (msg.from == MainMsg.FROM_SEARCHLOCKACTIVITY) {
                lockBeanList = MyDBHelper.getLockBeanList();
                refreshLockList();
                if (lockBeanNow == null || !lockBeanNow.lockserialId.equals(msg.lockserial)) {
                    lockBeanNow = MyDBHelper.getLockBean(msg.lockserial);
                }
                leftMenuFragment.setCheck(R.id.tv_lock_record);
            }
        } else if (baseMsg instanceof SearchLockBleMsg) {
            SearchLockBleMsg bleMsg = (SearchLockBleMsg) baseMsg;
            if (isActive) {
                isAutoConnect = true; //已经自动连接成功
                handler.removeMessages(RE_CONNECT_LOCK);
                ToastUtils.showToast(mContext, "门锁已连接");
            }
        } else if (baseMsg instanceof OperAdminMsg) {
            OperAdminMsg oMsg = (OperAdminMsg) baseMsg;
            String str = "";
            switch (oMsg.isSuc) {
//          cmd    0x13   现在为0x12
//#define 	MODIFY_ADMIN_PWD_SUCCESS					0		//修改管理员密码成功
//#define	MODIFY_ADMIN_PWD_VERIFY_OK					1		//验证管理员成功
//#define	MODIFY_ADMIN_PWD_VERIFY_FAILURE			2		//验证管理员失败
//#define	ADMIN_PWD_ENTER_FIRST_SUCCESS				3		//第一次输入密码成功
//#define	ADMIN_PWD_ENTER_FIRST_ERROR				4		//第一次输入密码错误
//#define 	ADMIN_PWD_ENTER_FIRST_TIME_OUT				5		//第一次输入密码超时
//#define	ADMIN_PWD_ENTER_SECOND_ERROR				6		//第二次输入密码错误
//#define 	ADMIN_PWD_ENTER_SECOND_NOT_SAME			7		//第二次输入与第一次不一样
//#define	ADMIN_PWD_ENTER_SECOND_TIME_OUT			8		//第二次输入密码超时
                case 0:
                    str="修改管理员密码成功";
                    break;
                case 1:
                    str="验证管理员成功";
                    break;
                case 2:
                    str="验证管理员失败";
                    break;
                case 3:
                    str="第一次输入密码成功";
                    break;
                case 4:
                    str="第一次输入密码错误";
                    break;
                case 5:
                    str="第一次输入密码超时";
                    break;
                case 6:
                    str="第二次输入密码错误";
                    break;
                case 7:
                    str="第二次输入与第一次不一样";
                    break;
                case 8:
                    str="第二次输入密码超时";
                    break;
            }
            ToastUtils.showToast(mContext, "" + str);

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isActive = false;
        MobclickAgent.onPause(this);
    }


    private ConnectivityManager connectivityManager;
    private NetworkInfo info;

    class MyReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
//                ToastUtils.showToast(MainActivity.this, "网络状态已经改变");
                connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                info = connectivityManager.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    netChangeOnLine();
                    String name = info.getTypeName();
                    Log.d("way", "当前网络名称：" + name);
                } else {
                    Log.d("way", "没有可用网络");
                }
            }
        }
    }

    /**
     * 网络变化有网了
     */
    private void netChangeOnLine() {


    }

    public interface IOnMenuChangeLisenter {
        void ChangeMenu(boolean key);
    }

    IOnMenuChangeLisenter iOnMenuChangeLisenter;

    public void setIOnMenuChangeLisenter(IOnMenuChangeLisenter iOnMenuChangeLisenter) {
        this.iOnMenuChangeLisenter = iOnMenuChangeLisenter;
    }


}
